package cn.wolfcode.crm.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对控制器的增强
 */
@ControllerAdvice
public class HandlerExceptionUtil {
    //标签 指定的异常在该方法中处理
    //括号里写我们处理什么方向的异常
    @ExceptionHandler(UnauthorizedException.class)
    public void handlerException(HttpServletResponse response, HandlerMethod method) throws IOException {
        //判断是普通请求,还是ajax请求(返回json数据)
        ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class);
        //如果是ajax请求就返回json数
        if(responseBody!=null){
            //不加这句就成字符串了
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(new ObjectMapper().writeValueAsString(new JSONResult(false,"您没有权限执行该操作")));
        }else {
            //如果不是就返回一个页面给他
            response.sendRedirect("/nopermission.jsp");
        }
    }

}
